<?php

namespace app\admin\controller;

use app\admin\common\Base;
use think\Db;
use ValueError;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use think\Session;

class Fix extends Base
{
	// 菜单列表
	public function index()
	{
		$data = $this->request->param();
		if (isset($data['ajax']) && $data['ajax'] == 1) {
			$page = isset($data['page']) ? $data['page'] : 1;
			$page = intval($page);
			$limit = isset($data['rows']) ? $data['rows'] : 10;
			$limit = intval($limit);
			$start = $limit * ($page - 1);

			if (isset($data['search'])) {
				if ($data['tj'] == 0) {
					$more_sn = more_sn($data['search']);
					if ($more_sn['status'] == 1) {
						$list = Db::name('fix')->whereOr('tagslogs_sn', 'like', '%' . $more_sn['sn'] . '%')->whereOr('tagslogs_sn', 'like', '%' . $data['search'] . '%')->order('id desc')->limit($start, $limit)->select();
						$count = Db::name('fix')->whereOr('tagslogs_sn', 'like', '%' . $data['search'] . '%')->whereOr('tagslogs_sn', 'like', '%' . $more_sn['sn'] . '%')->order('id desc')->count();
					} else {
						$list = Db::name('fix')->where('tagslogs_sn', 'like', '%' . $data['search'] . '%')->order('id desc')->limit($start, $limit)->select();
						$count = Db::name('fix')->where('tagslogs_sn', 'like', '%' . $data['search'] . '%')->order('id desc')->count();
					}
				} else {
					$good_id = Db::name('good')->where('name', 'like', '%' . $data['search'] . '%')->select();
					$good_id = array_column($good_id, 'id');
					$list = Db::name('fix')->where('good_id', 'in', $good_id)->order('id desc')->limit($start, $limit)->select();
					$count = Db::name('fix')->where('good_id', 'in', $good_id)->order('id desc')->count();
				}
			} else {
				$list = Db::name('fix')->order('id desc')->limit($start, $limit)->select();
				$count = Db::name('fix')->order('id desc')->count();
			}

			foreach ($list as $key => $value) {
				$list[$key]['good_name'] = Db::name('good')->where('id', $value['good_id'])->find()['name'];
				$tagslogs = Db::name('tagslogs')->where('sn', $value['tagslogs_sn'])->find();
				if ($tagslogs['addtime'] != 0) {
					$list[$key]['addtime'] = date('Y-m-d', $tagslogs['addtime']);
				}
				if ($tagslogs['outtime'] != 0) {
					$list[$key]['outtime'] = date('Y-m-d', $tagslogs['outtime']);
				}
				// 关联序列号
				$list[$key]['tagslogs_sn1'] = '';
				$more_sn = more_sn($list[$key]['tagslogs_sn']);
				if ($more_sn['status'] == 1) {
					$list[$key]['tagslogs_sn1'] = $more_sn['sn'];
				}
			}

			return $this->json_data($count, $list);
		}
		return $this->fetch();
	}

	public function details($id)
	{
		$data = $this->request->param();
		if (isset($data['ajax']) && $data['ajax'] == 1) {
			$fix = Db::name('fix')->where('id', $id)->find();
			// 查询序列号
			$more_sn = more_sn($fix['tagslogs_sn']);
			if (empty($more_sn['sn'])) {
				$pid_arr = [$id];
			} else {
				// 根据sn获取fix
				$fix1 = Db::name('fix')->where('tagslogs_sn', 'in', $more_sn['sn'])->select();
				$pid_arr = array_column($fix1, 'id');
				array_push($pid_arr, $id);
			}

			$page = isset($data['page']) ? $data['page'] : 1;
			$page = intval($page);
			$limit = isset($data['rows']) ? $data['rows'] : 10;
			$limit = intval($limit);
			$start = $limit * ($page - 1);

			if (isset($data['search'])) {

				switch ($data['tj']) {
					case 0:
						$fix_details = Db::name('fix_details')->where('pid', 'in', $pid_arr)->where('danwei', 'like', '%' . $data['search'] . '%')->limit($start, $limit)->select();
						$count = Db::name('fix_details')->where('pid', 'in', $pid_arr)->where('danwei', 'like', '%' . $data['search'] . '%')->count();
						break;
					case 1:
						$fix_details = Db::name('fix_details')->where('pid', 'in', $pid_arr)->where('contacts', 'like', '%' . $data['search'] . '%')->limit($start, $limit)->select();
						$count = Db::name('fix_details')->where('pid', 'in', $pid_arr)->where('contacts', 'like', '%' . $data['search'] . '%')->count();
						break;
					case 2:
						$fix_details = Db::name('fix_details')->where('pid', 'in', $pid_arr)->where('personnel', 'like', '%' . $data['search'] . '%')->limit($start, $limit)->select();
						$count = Db::name('fix_details')->where('pid', 'in', $pid_arr)->where('personnel', 'like', '%' . $data['search'] . '%')->count();
						break;
					case 3:
						$fix_details = Db::name('fix_details')->where('pid', 'in', $pid_arr)->where('telphone', 'like', '%' . $data['search'] . '%')->limit($start, $limit)->select();
						$count = Db::name('fix_details')->where('pid', 'in', $pid_arr)->where('telphone', 'like', '%' . $data['search'] . '%')->count();
						break;
					case 4:
						$pfix = Db::name('fix')->where('id', 'in', $pid_arr)->where('tagslogs_sn', 'like', '%' . $data['search'] . '%')->select();
						if (empty($pfix)) {
							$fix_details = [];
							$count = 0;
						} else {

							$pid_arr = array_column($pfix, 'id');
							$fix_details = Db::name('fix_details')->where('pid', 'in', $pid_arr)->limit($start, $limit)->select();
							$count = Db::name('fix_details')->where('pid', 'in', $pid_arr)->count();
						}
						break;
					default:
						break;
				}
			} else {
				$fix_details = Db::name('fix_details')->where('pid', 'in', $pid_arr)->limit($start, $limit)->select();
				$count = Db::name('fix_details')->where('pid', 'in', $pid_arr)->count();
			}

			foreach ($fix_details as $key => $value) {
				$fix_details[$key]['good_name'] = Db::name('good')->where('id', $fix['good_id'])->find()['name'];
				$tagslogs = Db::name('tagslogs')->where('sn', $fix['tagslogs_sn'])->find();
				$fix_details[$key]['tagslogs_sn'] = $tagslogs['sn'];
				$fix_details[$key]['intime'] = $tagslogs['addtime'] == 0 ? '' : date('Y-m-d', $tagslogs['addtime']);
				$fix_details[$key]['outtime'] = $tagslogs['outtime'] == 0 ? '' : date('Y-m-d', $tagslogs['outtime']);
				$fix_details[$key]['date'] = $value['date'] == 0 ? 0 : date('Y-m-d', $value['date']);
				$fix_details[$key]['fixwhere'] = '用户添加';
				$fix_details[$key]['admin_name'] = Db::name('admin')->where('id', $value['admin_id'])->find()['username'];
				$fix_details[$key]['addtime'] = $value['addtime'] == 0 ? '' : date('Y-m-d H:i:s', $value['addtime']);
				$fix_details[$key]['check_name'] = Db::name('admin')->where('id', $value['check_id'])->find()['username'];
				$fix_details[$key]['checktime'] = $value['checktime'] == 0 ? '' : date('Y-m-d H:i:s', $value['checktime']);
				if ($value['where'] == 1) {
					$fix_details[$key]['fixwhere'] = '系统添加';
				}

				$fix_details[$key]['tagslogs_sn'] = Db::name('fix')->where('id', $fix_details[$key]['pid'])->value('tagslogs_sn');
				// 关联序列号
				$more_sn = more_sn($fix_details[$key]['tagslogs_sn']);
				$fix_details[$key]['tagslogs_sn1'] = '';
				if ($more_sn['status'] == 1) {
					$fix_details[$key]['tagslogs_sn1'] = $more_sn['sn'];
				}
			}
			return $this->json_data($count, $fix_details);
		}
		$this->assign('id', $id);
		return $this->fetch();
	}

	public function seeimgs($id)
	{
		$imgs = Db::name('fix_img')->where('pid', $id)->select();

		$this->assign('imgs', $imgs);
		return $this->fetch();
	}

	// 添加
	public function add()
	{
		return $this->fetch();
	}

	// 保存
	public function save()
	{
		$data = $this->request->param();
		$post = $data;
		// 判断保修是否存在
		$card = Db::name('card')->where(['tagslogs_sn' => $data['tagslogs_sn'], 'checkstatus' => 1])->find();
		if (empty($card)) {
			return ['status' => 0, 'msg' => '保修卡不存在或未激活'];
		}
		if (($card['starttime'] <= time()) && ($card['endtime'] >= time())) {
		} else {
			return ['status' => 0, 'msg' => '保修卡保修期限已过期'];
		}
		//先写维修表
		$temp = Db::name('fix')->where('tagslogs_sn', $data['tagslogs_sn'])->find();
		if ($temp) {
			$pid = $temp['id'];
			Db::name('fix')->where('id', $pid)->setInc('fixnum');
		} else {
			$goodstags_id = Db::name('tagslogs')->where('sn', $data['tagslogs_sn'])->find()['goodstags_id'];
			if ($goodstags_id) {
				$good_id = Db::name('goodstags')->where('id', $goodstags_id)->find()['good_id'];
				$fix['good_id'] = $good_id;
				$fix['tagslogs_sn'] = $data['tagslogs_sn'];
				$pid = Db::name('fix')->insertGetId($fix);
			} else {
				return ['status' => 0, 'msg' => 'sn不存在'];
			}
		}

		//写详情表
		$img = $data;
		unset($data['tagslogs_sn']);
		unset($data['img']);
		$data['date'] = strtotime($data['date']);
		$data['pid'] = $pid;
		$data['admin_id'] = Session::get('user_id');
		$data['addtime'] = time();
		$res = Db::name('fix_details')->insertGetId($data);
		if ($res) {
			if (isset($img['img'])) {
				$arr = [];
				foreach ($img['img'] as $key => $value) {
					$arr[$key]['imgurl'] = $value;
					$arr[$key]['pid'] = $res;
					$arr[$key]['addtime'] = time();
					$arr[$key]['updatetime'] = time();
				}
				Db::name('fix_img')->insertAll($arr);
			}
			// 发送通知
			$msg_temp = get_msg_temp(5);
			if ($msg_temp['is_on'] == 1) {
				if ($msg_temp['type'] == 1 || $msg_temp['type'] == 2) { //通知短信
					send_mobile_message($data['telphone'], "shpass", $post['tagslogs_sn']);
				}
				if ($msg_temp['type'] == 1 || $msg_temp['type'] == 3) { //通知邮箱
					if (!empty($data['email'])) {
						sendToMail($data['email'], $msg_temp['email_title'], $msg_temp['email_content']);
					}
				}
			}
			return ['status' => 1, 'msg' => '添加成功', 'pid' => $pid];
		} else {
			return ['status' => 0, 'msg' => '添加失败', 'pid' => $pid];
		}
	}


	// 维修统计
	public function desc()
	{
		$info['zl'] = Db::name('fix_details')->count(); //总量

		$min_time = mktime(0, 0, 0, 1, 1, date('Y')); //本年初时间戳
		$where['date'] = ['>=', $min_time];
		$info['year_num'] =  Db::name('fix_details')->where($where)->count(); //年次数
		$min_time = mktime(0, 0, 0, date('m'), 1, date('Y')); //本月初时间戳
		$where1['date'] = ['>=', $min_time];
		$info['mon_num'] =  Db::name('fix_details')->where($where1)->count(); //月次数
		$min_time =  mktime(0, 0, 0, date('m'), date('d') - date('w') + 1, date('y'));  //本周初时间戳
		$where2['date'] = ['>=', $min_time];
		$info['week_num'] =  Db::name('fix_details')->where($where2)->count(); //周次数
		//取当前时间的前12月

		$date_arr = [];

		for ($i = 12; $i > 0; $i--) {
			array_push($date_arr, date("Y-m", strtotime("-{$i} month")));
		}
		array_push($date_arr, date("Y-m"));


		$count_sum = [];

		foreach ($date_arr as $k => $val) {
			$starttime = $val . '-01 00:00:00';
			$endtime =  date('Y-m-d H:i:s', strtotime("$starttime +1 month -1 second"));
			array_push($count_sum, Db::name('fix_details')->where('date', '>=', strtotime($starttime))->where('date', '<=', strtotime($endtime))->count());
		}

		$sheng = Db::table('fix_details')->field('cause')->group('cause')->select();
		$sheng = array_to_arr($sheng, 'cause');
		$sheng_count = [];
		$s = [];
		foreach ($sheng as $k => $val) {
			$s[$val] = Db::name('fix_details')->where('cause', 'eq',  $val)->count();
			array_push($sheng_count, Db::name('fix_details')->where('cause', 'eq',  $val)->count());
		}
		//halt($sheng);
		//halt($s);
		$this->assign('s', $s);
		$this->assign('sheng', json_encode($sheng));
		$this->assign('sheng_count', json_encode($sheng_count));
		$this->assign('date_arr', json_encode($date_arr));
		$this->assign('count_sum', json_encode($count_sum));
		$this->assign('info', $info);
		return $this->fetch();
	}
	// 审核
	public function add_status()
	{
		$data = $this->request->param();
		$res = Db::name('card')->where('id', $data['id'])->update(['checkstatus' => $data['checkstatus']]);
		//写日志
		$temp = Db::name('card')->where('id', $data['id'])->find();
		if ($data['checkstatus'] == 1) {
			adminlog('保修卡：' . $temp['tagslogs_sn'], '审核通过');
		} else {
			adminlog('保修卡：' . $temp['tagslogs_sn'], '审核拒绝');
		}
		if ($res) {
			return ['status' => 1, 'msg' => '操作成功'];
		} else {
			return ['status' => 0, 'msg' => '操作失败'];
		}
	}

	public function daochu()
	{
		$data = $this->request->param();
		if (isset($data['pid'])) {
			if (isset($data['stime']) && !empty($data['stime'])) {
				$data['stime'] = strtotime($data['stime'] . ' 00:00:00');
				$data['etime'] = strtotime($data['etime'] . ' 23:59:59');
				$lists = Db::name('fix_details')->where('date', '>=', $data['stime'])->where('pid', $data['pid'])->where('date', '<=', $data['etime'])->order('id desc')->select();
			} else {
				$lists = Db::name('fix_details')->order('id desc')->where('pid', $data['pid'])->select();
			}
		} else {
			if (isset($data['stime']) && !empty($data['stime'])) {
				$data['stime'] = strtotime($data['stime'] . ' 00:00:00');
				$data['etime'] = strtotime($data['etime'] . ' 23:59:59');
				$lists = Db::name('fix_details')->where('date', '>=', $data['stime'])->where('date', '<=', $data['etime'])->order('id desc')->select();
			} else {
				$lists = Db::name('fix_details')->order('id desc')->select();
			}
		}

		foreach ($lists as $key => $value) {
			$fix = Db::name('fix')->where('id', $value['pid'])->find();

			$lists[$key]['good_name'] = Db::name('good')->where('id', $fix['good_id'])->find()['name'];
			$tagslogs = Db::name('tagslogs')->where('sn', $fix['tagslogs_sn'])->find();
			$lists[$key]['tagslogs_sn'] = $fix['tagslogs_sn'];
			$lists[$key]['fixnum'] = $fix['fixnum'];

			$lists[$key]['addtime'] = '';
			$lists[$key]['outtime'] = '';
			$lists[$key]['date'] = '';

			if ($tagslogs['addtime'] != 0) {
				$lists[$key]['addtime'] = date('Y-m-d', $tagslogs['addtime']);
			}
			if ($tagslogs['outtime'] != 0) {
				$lists[$key]['outtime'] = date('Y-m-d', $tagslogs['outtime']);
			}
			if ($value['date'] != 0) {
				$lists[$key]['date'] = date('Y-m-d', $value['date']);
			}
		}

		$spreadsheet = new Spreadsheet();
		$PHPSheet = $spreadsheet->getActiveSheet();

		$PHPSheet->setTitle("维修数据"); //给当前活动sheet设置名称
		$PHPSheet->setCellValue("A1", "产品名称")
			->setCellValue("B1", "序列号")
			->setCellValue("C1", "出库日期")
			->setCellValue("D1", "入库日期")
			->setCellValue("E1", "维修次数")
			->setCellValue("F1", "故障原因")
			->setCellValue("G1", "维修项目")
			->setCellValue("H1", "维修费用")
			->setCellValue("I1", "维修时间")
			->setCellValue("J1", "维修人员")
			->setCellValue("K1", "送检单位")
			->setCellValue("L1", "联系人")
			->setCellValue("M1", "联系电话");

		$styleArray = [
			'alignment' => [
				'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
			],
		];
		foreach ($lists as $key => $val) {
			$spreadsheet->setActiveSheetIndex(0)
				->setCellValue("A" . ($key + 2), $val['good_name'])
				->setCellValue("B" . ($key + 2), $val['tagslogs_sn'])
				->setCellValue("C" . ($key + 2), $val['outtime'])
				->setCellValue("D" . ($key + 2), $val['addtime'])
				->setCellValue("E" . ($key + 2), $val['fixnum'])
				->setCellValue("F" . ($key + 2), $val['cause'])
				->setCellValue("G" . ($key + 2), $val['project'])
				->setCellValue("H" . ($key + 2), $val['price'])
				->setCellValue("I" . ($key + 2), $val['date'])
				->setCellValue("J" . ($key + 2), $val['personnel'])
				->setCellValue("K" . ($key + 2), $val['danwei'])
				->setCellValue("L" . ($key + 2), $val['contacts'])
				->setCellValue("M" . ($key + 2), $val['telphone']);
			$spreadsheet->setActiveSheetIndex(0)->getStyle('A' . ($key + 2))->applyFromArray($styleArray);
		}

		$spreadsheet->getActiveSheet()->getColumnDimension('A')->setWidth(50);
		$spreadsheet->getActiveSheet()->getColumnDimension('B')->setWidth(20);
		$spreadsheet->getActiveSheet()->getColumnDimension('C')->setWidth(15);
		$spreadsheet->getActiveSheet()->getColumnDimension('D')->setWidth(15);

		$time = date('Y-m-d', time());
		// Redirect output to a client’s web browser (Xlsx)
		header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
		header('Content-Disposition: attachment;filename="维修数据' . $time . '.xlsx"');
		header('Cache-Control: max-age=0');
		// If you're serving to IE 9, then the following may be needed
		header('Cache-Control: max-age=1');
		// If you're serving to IE over SSL, then the following may be needed
		header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
		header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
		header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
		header('Pragma: public'); // HTTP/1.0

		$writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Xlsx');
		$writer->save('php://output');
	}

	// 待审核
	public function pre_list()
	{
		$data = $this->request->param();
		if (isset($data['ajax']) && $data['ajax'] == 1) {
			$map = '';
			$page = isset($data['page']) ? $data['page'] : 1;
			$page = intval($page);
			$limit = isset($data['rows']) ? $data['rows'] : 10;
			$limit = intval($limit);
			$start = $limit * ($page - 1);

			if ($map == '') {
				$list = Db::name('card')->where('checkstatus', 0)->order('id desc')->limit($start, $limit)->select();

				$count = count($list);
			} else {
				$list = Db::name('card')->where('checkstatus', 0)->order('id desc')->limit($start, $limit)->select();
				$count = count($list);
			}

			foreach ($list as $key => $value) {
				// 查询标签
				$goodstags = Db::name('tagslogs')->where('sn', $value['tagslogs_sn'])->find();
				$good_id = Db::name('goodstags')->where('id', $goodstags['goodstags_id'])->value('good_id');
				$good = Db::name('good')->where('id', $good_id)->find();
				$list[$key]['good_name'] = $good['name'];
				$list[$key]['goodstags_sn'] = $goodstags['sn'];
				$list[$key]['good_model'] = $good['model'];
				$list[$key]['endtime'] = date('Y-m-d H:i:s', $value['endtime']);
				switch ($value['checkstatus']) {
					case 0:
						$list[$key]['checkstatus_name'] = '待审核';
						break;
					case 1:
						$list[$key]['checkstatus_name'] = '通过';
						break;
					case 2:
						$list[$key]['checkstatus_name'] = '拒绝';
						break;
				}
			}

			return $this->json_data($count, $list);
		}
		return $this->fetch();
	}

	// 已经审核
	public function done_list()
	{
		$data = $this->request->param();
		if (isset($data['ajax']) && $data['ajax'] == 1) {
			$map = '';
			$page = isset($data['page']) ? $data['page'] : 1;
			$page = intval($page);
			$limit = isset($data['rows']) ? $data['rows'] : 10;
			$limit = intval($limit);
			$start = $limit * ($page - 1);

			if ($map == '') {
				$list = Db::name('card')->where('checkstatus', '>', 0)->order('id desc')->limit($start, $limit)->select();
				$count = count($list);
			} else {
				$list = Db::name('card')->where('checkstatus', '>', 0)->order('id desc')->limit($start, $limit)->select();
				$count = count($list);
			}

			foreach ($list as $key => $value) {
				// 查询标签
				$goodstags = Db::name('tagslogs')->where('sn', $value['tagslogs_sn'])->find();
				$good_id = Db::name('goodstags')->where('id', $goodstags['goodstags_id'])->value('good_id');
				$good = Db::name('good')->where('id', $good_id)->find();
				$list[$key]['good_name'] = $good['name'];
				$list[$key]['goodstags_sn'] = $goodstags['sn'];
				$list[$key]['good_model'] = $good['model'];
				$list[$key]['endtime'] = date('Y-m-d H:i:s', $value['endtime']);
				switch ($value['checkstatus']) {
					case 0:
						$list[$key]['checkstatus_name'] = '待审核';
						break;
					case 1:
						$list[$key]['checkstatus_name'] = '通过';
						break;
					case 2:
						$list[$key]['checkstatus_name'] = '拒绝';
						break;
				}
			}

			return $this->json_data($count, $list);
		}
		return $this->fetch();
	}
}
